package com.ruoyi.project.jxy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.jxy.domain.AsrRecord;
import com.ruoyi.project.jxy.domain.DownloadHistory;
import com.ruoyi.project.jxy.service.IDownloadHistoryService;
import com.ruoyi.project.jxy.service.impl.FileInfoThread;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.jxy.domain.TtsRecord;
import com.ruoyi.project.jxy.service.ITtsRecordService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 语音合成记录Controller
 *
 * @author ruoyi
 * @date 2020-09-07
 */
@RestController
@RequestMapping("/jxy/ttsRecord")
public class TtsRecordController extends BaseController {
    @Autowired
    private ITtsRecordService ttsRecordService;
    @Autowired
    private IDownloadHistoryService downloadHistoryService;

    /**
     * 查询语音合成记录列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(TtsRecord ttsRecord) {
        startPage();
        QueryWrapper<TtsRecord> queryWrapper = new QueryWrapper<TtsRecord>();
        if (StringUtils.isNotBlank(ttsRecord.getRegion())) {
            queryWrapper.eq("region", ttsRecord.getRegion());
        }
        if (StringUtils.isNotBlank(ttsRecord.getTheme())) {
            queryWrapper.eq("theme", ttsRecord.getTheme());
        }
        if (StringUtils.isNotBlank(ttsRecord.getName())) {
            queryWrapper.like("name", ttsRecord.getName());
        }
        if (StringUtils.isNotBlank(ttsRecord.getSex())) {
            queryWrapper.eq("sex", ttsRecord.getSex());
        }
        if (ttsRecord.getAge() != null) {
            queryWrapper.eq("age", ttsRecord.getAge());
        }
        if (StringUtils.isNotBlank(ttsRecord.getPath())) {
            queryWrapper.eq("path", ttsRecord.getPath());
        }
        if (StringUtils.isNotBlank(ttsRecord.getDisplayName())) {
            queryWrapper.like("display_name", ttsRecord.getDisplayName());
        }
        if (StringUtils.isNotBlank(ttsRecord.getFileMd5())) {
            queryWrapper.eq("file_md5", ttsRecord.getFileMd5());
        }
        if (StringUtils.isNotBlank(ttsRecord.getContent())) {
            queryWrapper.eq("content", ttsRecord.getContent());
        }
        if (ttsRecord.getDuration() != null) {
            queryWrapper.eq("duration", ttsRecord.getDuration());
        }
        if (StringUtils.isNotBlank(ttsRecord.getDurationText())) {
            queryWrapper.eq("duration_text", ttsRecord.getDurationText());
        }
        if (ttsRecord.getFileSize() != null) {
            queryWrapper.eq("file_size", ttsRecord.getFileSize());
        }
        if (StringUtils.isNotBlank(ttsRecord.getCreateUser())) {
            queryWrapper.eq("create_user", ttsRecord.getCreateUser());
        }
        if (StringUtils.isNotBlank(ttsRecord.getUpdateUser())) {
            queryWrapper.eq("update_user", ttsRecord.getUpdateUser());
        }
        List<TtsRecord> list = ttsRecordService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出语音合成记录列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:export')")
    @Log(title = "语音合成记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TtsRecord ttsRecord) {
        QueryWrapper<TtsRecord> queryWrapper = new QueryWrapper<TtsRecord>(ttsRecord);
        List<TtsRecord> list = ttsRecordService.list(queryWrapper);
        ExcelUtil<TtsRecord> util = new ExcelUtil<TtsRecord>(TtsRecord.class);
        return util.exportExcel(list, "ttsRecord");
    }

    /**
     * 获取语音合成记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ttsRecordService.getById(id));
    }

    /**
     * 新增语音合成记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:add')")
    @Log(title = "语音合成记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TtsRecord ttsRecord) {
        String md5 = DigestUtils.md5Hex(FileUtil.readBytes(FileUtil.newFile(ttsRecord.getPath().replace("/profile", RuoYiConfig.getProfile()))));
        ttsRecord.setFileMd5(md5);
        ttsRecord.setCreateTime(new Date());
        ttsRecord.setCreateUser(SecurityUtils.getUsername());
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("file_md5", ttsRecord.getFileMd5());
        Long duration = FileInfoThread.getDuration(FileUtil.newFile(ttsRecord.getPath().replace("/profile", RuoYiConfig.getProfile())));
        ttsRecord.setDuration(duration);
        ttsRecord.setDurationText(FileInfoThread.getDuration(duration));
        int check = ttsRecordService.count(wrapper);
        if (check != 0) {
            return AjaxResult.error("该文件已存在");
        }
        return toAjax(ttsRecordService.save(ttsRecord) ? 1 : 0);
    }

    /**
     * 修改语音合成记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:edit')")
    @Log(title = "语音合成记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TtsRecord ttsRecord) {
        String md5 = DigestUtils.md5Hex(FileUtil.readBytes(FileUtil.newFile(ttsRecord.getPath().replace("/profile", RuoYiConfig.getProfile()))));
        ttsRecord.setFileMd5(md5);
        Long duration = FileInfoThread.getDuration(FileUtil.newFile(ttsRecord.getPath().replace("/profile", RuoYiConfig.getProfile())));
        ttsRecord.setDuration(duration);
        ttsRecord.setDurationText(FileInfoThread.getDuration(duration));
        ttsRecord.setUpdateTime(new Date());
        ttsRecord.setUpdateUser(SecurityUtils.getUsername());
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("file_md5", ttsRecord.getFileMd5());
        wrapper.ne("id", ttsRecord.getId());
        int check = ttsRecordService.count(wrapper);
        if (check != 0) {
            return AjaxResult.error("该文件已存在");
        }

        return toAjax(ttsRecordService.updateById(ttsRecord) ? 1 : 0);
    }

    /**
     * 删除语音合成记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:remove')")
    @Log(title = "语音合成记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ttsRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 导出语音合成数据
     */
    @PreAuthorize("@ss.hasPermi('jxy:ttsRecord:zip')")
    @Log(title = "语音合成打包", businessType = BusinessType.OTHER)
    @GetMapping("/zip")
    public AjaxResult zip(TtsRecord ttsRecord) {
        QueryWrapper<TtsRecord> queryWrapper = new QueryWrapper<TtsRecord>();
        if (StringUtils.isNotBlank(ttsRecord.getRegion())) {
            queryWrapper.eq("region", ttsRecord.getRegion());
        }
        if (StringUtils.isNotBlank(ttsRecord.getTheme())) {
            queryWrapper.eq("theme", ttsRecord.getTheme());
        }
        if (StringUtils.isNotBlank(ttsRecord.getName())) {
            queryWrapper.like("name", ttsRecord.getName());
        }
        if (StringUtils.isNotBlank(ttsRecord.getSex())) {
            queryWrapper.eq("sex", ttsRecord.getSex());
        }
        if (ttsRecord.getAge() != null) {
            queryWrapper.eq("age", ttsRecord.getAge());
        }
        if (StringUtils.isNotBlank(ttsRecord.getPath())) {
            queryWrapper.eq("path", ttsRecord.getPath());
        }
        if (StringUtils.isNotBlank(ttsRecord.getDisplayName())) {
            queryWrapper.like("display_name", ttsRecord.getDisplayName());
        }
        List<TtsRecord> list = ttsRecordService.list(queryWrapper);
        DownloadHistory downloadHistory = new DownloadHistory();
        BeanUtil.copyProperties(ttsRecord, downloadHistory);
        downloadHistory.setId(null);
        downloadHistory.setType("1");
        downloadHistory.setCreateUser(SecurityUtils.getUsername());
        downloadHistory.setCreateTime(new Date());
        downloadHistoryService.save(downloadHistory);
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                String baseDir = RuoYiConfig.getProfile();
                //打包的文件夹名称
                String fileName = DateUtils.dateTimeNow();
                String fileDir = baseDir + "/download/" + fileName;
                String wavPath = fileDir + "/wav";
                String txtPath = fileDir + "/txt";
                //新建wav文件夹
                FileUtil.mkdir(wavPath);
                //新建txt 文件夹
                FileUtil.mkdir(txtPath);
                for (TtsRecord record :
                        list) {
                    //复制文件
                    //每一个文件的真实地址
                    String realFilePath = record.getPath().replace("/profile", baseDir);
                    //复制音频文件
                    FileUtil.copy(realFilePath, wavPath, true);
                    //获取文件名
                    String name = record.getDisplayName().substring(0, record.getDisplayName().indexOf("."));
                    //生成txt 文件
                    FileUtil.writeString(record.getContent(), FileUtil.newFile(txtPath + "/" + name + ".txt"), Charset.defaultCharset());
                }
                File zip = ZipUtil.zip(fileDir);
                //压缩包真实名称
                String zipPath = zip.getAbsolutePath();
                String zipName = zip.getName();
                //转换为可下载路径
                String downloadPath = zipPath.replace(baseDir, "/profile");
                downloadHistory.setPath(downloadPath);
                downloadHistory.setDisplayName(zipName);
                downloadHistoryService.updateById(downloadHistory);
            }
        });
        return AjaxResult.success();
    }
}
